package com.wn.icloud.auth.controller;

import com.wn.icloud.auth.configuration.KeyConfiguration;
import com.wn.icloud.auth.service.AuthClientService;
import com.wn.icloud.auth.service.AuthService;
import com.wn.icloud.common.msg.ObjectRestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by Rainer on 2017/9/10.
 */
@RestController
@RequestMapping("/client")
public class ClientController {
    @Autowired
    private AuthClientService authClientService;
    @Autowired
    private KeyConfiguration keyConfiguration;
    @Autowired
    private AuthService authService;

    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public ObjectRestResponse getAccessToken(String clientId, String secret) throws Exception {
        return new ObjectRestResponse<String>().data(authClientService.apply(clientId, secret));
    }

    @RequestMapping(value = "/myClient", method = RequestMethod.POST)
    public ObjectRestResponse getAllowedClient(String serviceId, String secret) {
        return new ObjectRestResponse<List<String>>().data(authClientService.getAllowedClient(serviceId, secret));
    }

    @RequestMapping(value = "/servicePubKey", method = RequestMethod.POST)
    public ObjectRestResponse<byte[]> getServicePublicKey(@RequestParam("clientId") String clientId, @RequestParam("secret") String secret) throws Exception {

        authClientService.validate(clientId, secret);
        return new ObjectRestResponse<byte[]>().data(keyConfiguration.getServicePubKey());
    }

    @RequestMapping(value = "/userPubKey", method = RequestMethod.POST)
    public ObjectRestResponse<byte[]> getUserPublicKey(@RequestParam("clientId") String clientId, @RequestParam("secret") String secret) throws Exception {
        System.out.println("");
        authClientService.validate(clientId, secret);
        return new ObjectRestResponse<byte[]>().data(keyConfiguration.getUserPubKey());
    }

    @GetMapping("/client/testToken")
    ObjectRestResponse<String> getTestToken(@RequestParam("userName") String userName, @RequestParam("userId") String userId) throws Exception {
        String token = authService.genTestToken(userName, userId);
        return new ObjectRestResponse<String>().data(token);
    }


}
